#include <my_header.h>

/* Usage: ./6_server_epoll */
typedef struct client_s
{
    int alive;
    time_t last_time;
}client_t;
int main(void){                                  
    char *ip = "192.168.229.128";
    char *port = "8080";

    int socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    ERROR_CHECK(socket_fd, -1, "socket");

    int reuse = 1;
    int res_set = setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
    ERROR_CHECK(res_set, -1, "setsockopt");

    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(atoi(port));
    server_addr.sin_addr.s_addr = inet_addr(ip);
    
    int res_bind = bind(socket_fd, (struct sockaddr *)&server_addr, sizeof(server_addr));
    ERROR_CHECK(res_bind, -1, "bind");

    int res_lis = listen(socket_fd, 10);
    ERROR_CHECK(res_lis, -1, "listen");

    int net_fd = accept(socket_fd, NULL, 0);
    ERROR_CHECK(net_fd, -1, "accept");

    // 创建epoll对象
    int epoll_fd = epoll_create(1);
    ERROR_CHECK(epoll_fd, -1, "epoll_create");

    // 设计监听集合
    struct epoll_event event;
    event.events = EPOLLIN;
    event.data.fd = net_fd;
    int res_epolctl = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, net_fd, &event);
    ERROR_CHECK(res_epolctl, -1, "epoll_ctl");

    event.data.fd = STDIN_FILENO;
    int res_epolctl2 = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, STDIN_FILENO, &event);
    ERROR_CHECK(res_epolctl2, -1, "epoll_ctl");

    int size = 0;

    while(1)
    {
        // 构建就绪接收数组
        struct epoll_event events[2];
        // 监听 进入阻塞状态，直到监听的设备就绪或者超时
        int num  = epoll_wait(epoll_fd, events, 2, 0);
        // 遍历就绪集合
        for(int i = 0; i<num; i++)
        {
            int cfd = events[i].data.fd;
            if(cfd == STDIN_FILENO)
            {
                // 读取标准输入
                char buf[60] = { 0 };
                read(STDIN_FILENO, buf, sizeof(buf));
                // 发送
                int res_send = send(net_fd, buf, strlen(buf), 0);
                ERROR_CHECK(res_send, -1, "send");
            }else if(cfd == net_fd)
            {
                // 读取socket数据
                char buf[60] = {0};
                int res_recv = recv(net_fd, buf, sizeof(buf), 0);
                if(res_recv == 0)
                {
                    printf("client closed \n");
                    goto end;
                }
                printf("client message \n");
            }
        }       
    }

end:
    close(net_fd);
    close(socket_fd);
    return 0;
}


